<template>
  <div class="refund-approval-container">
    <el-card shadow="never" class="main-card">
      <template #header>
        <div class="card-header">
          <span>退款申请审核</span>
        </div>
      </template>

      <!-- 筛选表单 -->
      <el-form :model="searchParams" class="search-form">
        <el-form-item label="老人姓名" style="flex-grow: 1;">
          <el-input v-model="searchParams.elderlyName" placeholder="请输入老人姓名" clearable />
        </el-form-item>
        <el-form-item label="审核状态" style="flex-grow: 1;">
          <el-select v-model="searchParams.status" placeholder="请选择状态" clearable>
            <!-- FIX: value 改为小写以匹配后端 -->
            <el-option label="待审核" value="pending"></el-option>
            <el-option label="已通过" value="approved"></el-option>
            <el-option label="已拒绝" value="rejected"></el-option>
            <el-option label="已完成" value="completed"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格容器 -->
      <div class="table-container">
        <el-table 
          :data="tableData" 
          v-loading="loading" 
          border
          stripe
          class="refund-table"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        >
          <el-table-column type="index" label="序号" width="60" align="center" fixed="left" />
          <el-table-column prop="id" label="申请ID" width="100" align="center" />
          <el-table-column prop="elderlyName" label="老人姓名" width="100" />
          <el-table-column prop="billId" label="关联账单编号" width="140" align="center" />
          <el-table-column prop="amount" label="退款金额 (元)" width="120" align="right">
             <template #default="{ row }">
              <span v-if="row.amount" style="color: #F56C6C; font-weight: bold;">¥ {{ row.amount.toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="reason" label="申请原因" show-overflow-tooltip min-width="200" />
          <el-table-column prop="createdAt" label="申请时间" width="160" align="center" />
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="statusTagType(row.status)">
                {{ statusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <!-- NEW: 扩展操作列 -->
          <el-table-column label="操作" width="180" align="center" fixed="right">
            <template #default="{ row }">
              <el-button 
                v-if="row.status === 'pending'"
                type="primary" link :icon="Edit" @click="handleReview(row)"
              >
                审核
              </el-button>
              <el-button
                v-if="row.status === 'approved'"
                type="success" link :icon="CircleCheck" @click="handleComplete(row.id)"
              >
                完成退款
              </el-button>
              <el-button
                v-if="row.status === 'pending' || row.status === 'rejected'"
                type="danger" link :icon="Delete" @click="handleDelete(row.id)"
              >
                删除
              </el-button>
              <span v-if="row.status === 'completed'">-</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

       <!-- 分页 -->
      <el-pagination
        v-if="total > 0"
        class="pagination-container"
        :current-page="pagination.pageNum"
        :page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :layout="paginationLayout"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 审核对话框 (无变化，保持原样) -->
    <el-dialog v-model="dialogVisible" title="退款申请审核" :width="dialogWidth" :close-on-click-modal="false" destroy-on-close center>
        <!-- ... 对话框内容与之前相同 ... -->
        <el-descriptions :column="dialogDescColumn" border>
            <el-descriptions-item label="申请ID">{{ currentRequest.id }}</el-descriptions-item>
            <el-descriptions-item label="老人姓名">{{ currentRequest.elderlyName }}</el-descriptions-item>
            <el-descriptions-item label="退款金额">
              <el-tag v-if="currentRequest.amount" type="danger">¥ {{ currentRequest.amount.toFixed(2) }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="关联账单" :span="2">{{ currentRequest.billId }}</el-descriptions-item>
            <el-descriptions-item label="申请原因" :span="3">{{ currentRequest.reason }}</el-descriptions-item>
        </el-descriptions>
        <el-form :model="reviewForm" :rules="reviewRules" ref="reviewFormRef" :label-width="labelWidth" style="margin-top: 20px;">
            <el-form-item label="审核结果" prop="status">
                <el-radio-group v-model="reviewForm.status" :class="{ 'mobile-radio': isMobile }">
                    <el-radio label="approved" :size="radioSize" border>通过申请</el-radio>
                    <el-radio label="rejected" :size="radioSize" border>驳回申请</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="审核意见" prop="remarks">
                <el-input v-model="reviewForm.remarks" type="textarea" :rows="3" placeholder="请输入审核意见" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitReview" :loading="submitLoading">确 认</el-button>
            </div>
        </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, onUnmounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Refresh, Edit, Delete, CircleCheck } from '@element-plus/icons-vue';
// NEW: 导入更多API
import { getRefundRecordPage, approveRefundRequest, completeRefund, deleteRefundRecord } from '@/api/refund'; 

// --- 响应式监听等部分保持不变 ---
const screenWidth = ref(window.innerWidth);
const updateScreenWidth = () => { screenWidth.value = window.innerWidth; };
onMounted(() => {
  window.addEventListener('resize', updateScreenWidth);
  fetchData();
});
onUnmounted(() => { window.removeEventListener('resize', updateScreenWidth); });
const isMobile = computed(() => screenWidth.value < 768);
const paginationLayout = computed(() => isMobile.value ? "prev, pager, next" : "total, sizes, prev, pager, next, jumper");
const dialogWidth = computed(() => isMobile.value ? '90%' : '600px');
const dialogDescColumn = computed(() => isMobile.value ? 1 : 2);
const labelWidth = computed(() => isMobile.value ? '80px' : '100px');
const radioSize = computed(() => isMobile.value ? 'default' : 'large');

// --- 状态定义 ---
const loading = ref(true);
const submitLoading = ref(false);
const dialogVisible = ref(false);

const searchParams = reactive({
  elderlyName: '',
  status: '',
});

const pagination = reactive({ pageNum: 1, pageSize: 10, });
const total = ref(0);
const tableData = ref([]);
const currentRequest = ref({}); 
const reviewFormRef = ref(null); 
const reviewForm = reactive({
  refundId: null,
  status: 'approved',
  remarks: '',
});
const reviewRules = reactive({
  status: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
  remarks: [{ validator: (rule, value, callback) => {
      if (reviewForm.status === 'rejected' && !value) {
        callback(new Error('驳回申请时，必须填写审核意见'));
      } else { callback(); }
    }, trigger: 'blur'
  }],
});

// --- API 调用方法 ---
const fetchData = async () => { /* ... 此方法无变化 ... */ 
  loading.value = true;
  try {
    const params = { ...searchParams, ...pagination };
    const res = await getRefundRecordPage(params);
    tableData.value = res.records || [];
    total.value = res.total || 0;
  } catch (error) {
    console.error("Error fetching refund data:", error);
    ElMessage.error('网络错误，请稍后重试');
  } finally { loading.value = false; }
};
const handleSearch = () => { pagination.pageNum = 1; fetchData(); };
const handleReset = () => {
  searchParams.elderlyName = '';
  searchParams.status = '';
  pagination.pageNum = 1;
  fetchData();
};
const handleSizeChange = (size) => { pagination.pageSize = size; fetchData(); };
const handleCurrentChange = (page) => { pagination.pageNum = page; fetchData(); };

// FIX: 状态文本转换，兼容小写
const statusText = (status) => {
  const map = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝',
    completed: '已完成'
  };
  return map[status] || '未知';
};

// FIX: 状态标签类型转换，兼容小写
const statusTagType = (status) => {
  const map = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger',
    completed: 'info'
  };
  return map[status] || 'info';
};

const handleReview = (row) => { /* ... 此方法无变化 ... */ 
  currentRequest.value = { ...row };
  reviewForm.refundId = row.id;
  reviewForm.status = 'approved';
  reviewForm.remarks = '';
  dialogVisible.value = true;
};
const submitReview = async () => { /* ... 此方法无变化 ... */ 
  if (!reviewFormRef.value) return;
  await reviewFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true;
      try {
        const res = await approveRefundRequest(reviewForm);
        ElMessage.success('审核操作成功！');
        dialogVisible.value = false;
        await fetchData();
      } catch (error) {
        console.error("Error submitting review:", error);
        ElMessage.error('提交审核失败，请稍后重试');
      } finally { submitLoading.value = false; }
    }
  });
};

// NEW: 完成退款操作
const handleComplete = async (refundId) => {
  try {
    await ElMessageBox.confirm('确认此笔退款已在线下完成，并将状态标记为"已完成"吗？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'success',
    });
    const res = await completeRefund(refundId);
    ElMessage.success('操作成功！');
    fetchData();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Error completing refund:', error);
      ElMessage.error('操作失败，请稍后重试');
    }
  }
};

// NEW: 删除退款记录
const handleDelete = async (refundId) => {
  try {
    await ElMessageBox.confirm('确定要删除这条退款申请记录吗？此操作不可恢复。', '警告', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
    });
    const res = await deleteRefundRecord(refundId);
    ElMessage.success('删除成功！');
    // 如果删除后当前页没数据了，跳到前一页
    if (tableData.value.length === 1 && pagination.pageNum > 1) {
      pagination.pageNum--;
    }
    fetchData();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Error deleting refund:', error);
      ElMessage.error('删除失败，请稍后重试');
    }
  }
};

</script>

<style scoped>
/* 修复侧边栏收缩时页面溢出的问题 */
.refund-approval-container {
  /* 关键修复：确保容器不会超出父容器宽度 */
  width: 99%;
  max-width: 100%; /* 防止宽度超出 */
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
  box-sizing: border-box;
  background: #fafbfc;
  overflow: hidden; /* 防止内容溢出 */
}

.main-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 防止内容溢出卡片 */
  min-width: 0; /* 关键：允许弹性收缩 */
}

.main-card :deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 让内部的table-container自己处理滚动 */
  padding: 20px;
  min-width: 0; /* 关键：允许弹性收缩 */
}

.card-header {
  font-size: 18px;
  font-weight: 500;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 20px;
  min-width: 0; /* 允许弹性收缩 */
}

.search-form .el-form-item {
  margin-bottom: 0 !important;
  min-width: 0; /* 允许弹性收缩 */
}

.table-container {
  flex: 1;
  overflow: auto; /* 关键：让表格可以在容器内部滚动 */
  min-width: 0; /* 关键：允许弹性收缩 */
}

/* 修复表格在小屏幕下的显示 */
.refund-table {
  min-width: 1200px; /* 设置表格最小宽度，确保所有列都能正常显示 */
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0; /* 分页器不收缩 */
}

.dialog-footer {
  text-align: center;
}

/* 响应式处理 */
@media (max-width: 768px) {
  .refund-approval-container {
    padding: 10px;
  }
  
  .main-card :deep(.el-card__body) {
    padding: 15px;
  }
  
  .search-form {
    gap: 10px;
  }
  
  .refund-table {
    min-width: 800px; /* 移动端减少最小宽度 */
  }
}

/* 确保在极小屏幕下也能正常显示 */
@media (max-width: 480px) {
  .refund-approval-container {
    padding: 8px;
  }
  
  .main-card :deep(.el-card__body) {
    padding: 10px;
  }
}
</style>